package com.ykefu.assign.netty.netty.websocket;

import com.ykefu.assign.domain.WebSocketServerResponseBody;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * @author likai
 * @date 2020/4/18 18:54
 * @email likai@7moor..com
 * @desc
 */
public class HandlerConnect {

    private static final Logger  LOGGER = LoggerFactory.getLogger(HandlerConnect.class);

    /**
     * 连接处理
     * @param context
     */
    public void connect(ChannelHandlerContext context){
        //分发连接唯一ID
        String uuid = UUID.randomUUID().toString();
        String content = WebSocketServerResponseBody.buildSuccess(uuid).toJSON();
        context.channel().writeAndFlush(new TextWebSocketFrame(content));
        //保存
        LOGGER.info("socket 连接：{}",uuid);
        ChannelManager.getInstance().save(uuid,context);
    }


    private HandlerConnect(){}


    public static HandlerConnect getInstance(){
        return InnerHandlerConnect.instance;
    }

    private static class InnerHandlerConnect{
        private static HandlerConnect instance = new HandlerConnect();
    }
}
